// 验证并提交表单
function checkForm(formId) {
	switch (formId) {
		case 'registerForm':
			$.validator.setDefaults({ 
				submitHandler: function(form) { 
					form.submit(); 
				},
				highlight: function(input) {
					$(input).addClass("wss-highlight");
				},
				unhighlight: function(input) {
					$(input).removeClass("wss-highlight");
				}
			}); 
			
			// 自定义验证规则 - 验证用户名格式
			$.validator.addMethod(
				"validateUsername", 
				function(value) {
					var result = value.match(/^[A-Za-z0-9_-]+$/);
					if(result == null) {
						return false;
					} else {
						return true;
					}
				}, 
				'用户名只允许出现字母,数字,下划线,中横线'
			);
			
			// 自定义验证规则 - 验证用户名是否存在
			$.validator.addMethod(
				"validateUsernameExist", 
				function(value) {
					var sign = false;
					$.ajax({
						async: false,
						type: "POST",
						url: "/users/checkUsernameExist",
						data: 'username=' + $('input[id="data[username]"]').attr('value'),
						dataType: "json",
						timeout: 7000,
						success: function(result) {
							sign = result.sign;
						},
						error: function() {
							//alert('数据读取错误,请重试..');
							return false;
						}
					});
					
					return sign;
				}, 
				'此用户名已被使用'
			);
			
			// 自定义验证规则 - 验证邮箱是否存在
			$.validator.addMethod(
				"validateEmailExist", 
				function(value) {
					var sign = false;
					$.ajax({
						async: false,
						type: "POST",
						url: "/users/checkEmailExist",
						data: 'email=' + $('input[id="data[email]"]').attr('value'),
						dataType: "json",
						timeout: 7000,
						success: function(result) {
							sign = result.sign;
						},
						error: function() {
							//alert('数据读取错误,请重试..');
							return false;
						}
					});
					
					return sign;
				}, 
				'此邮箱已被使用'
			);
			
			// 自定义验证规则 - 验证邮箱是否存在
			$.validator.addMethod(
				"validatePhoneExist", 
				function(value) {
					var sign = false;
					$.ajax({
						async: false,
						type: "POST",
						url: "/users/checkPhoneExist",
						data: 'phone=' + $('input[id="data[phone]"]').attr('value'),
						dataType: "json",
						timeout: 7000,
						success: function(result) {
							sign = result.sign;
						},
						error: function() {
							//alert('数据读取错误,请重试..');
							return false;
						}
					});
					
					return sign;
				}, 
				'此手机号已被使用'
			);
			
			// 自定义验证规则 - 验证验证码
			$.validator.addMethod(
				"validateVerification", 
				function(value) {
					var sign = false;
					$.ajax({
						async: false,
						type: "POST",
						url: "/users/getVerificationCode",
						data: "verificationCode=" + $("#data\\[verificationCode\\]").val(),
						dataType: "json",
						timeout: 7000,
						success: function(result) {	
							sign = result.sign;
						},
						error: function() {
							//alert('数据读取错误,请重试..');
							return false;
						}
					});
					
					if (sign == false) {
						changeVerificationImg('verificationImg');
					}
					return sign;
				}, 
				'输入的验证码有误,请重试'
			);
			
			$(function() {
				$("#registerForm").validate({
					errorClass: "validateError",
					onkeyup: false,
					errorPlacement: function(error, element) {
						element.parent("div").after('<div class="validateError"></div>');
						error.appendTo(element.parent("div").next('div[class="validateError"]'));
					},
					success: function(label) {
						label.parent("div[class='validateError']").remove();
					},
					rules: {
						/*"data[username]": {
							required: true,
							rangelength: [4, 16],
							validateUsername: true,
							validateUsernameExist: true
						},*/
						"data[email]": {
							required: true,
							email: true,
							validateEmailExist: true
						},
						"data[password]": {
							required: true,
							rangelength: [6, 16]
						},
						"data[confirm_password]": {
							required: true,
							equalTo: '#data\\[password\\]'
						},
						"data[realname]": {
							required: true
						},
						"data[phone]": {
							required: true,
							digits: true,
							rangelength: [11, 11],
							validatePhoneExist: true
						},
						"data[grade_id]": {
							required: true,
							digits: true
						},
						"data[verificationCode]": {
							required: true,
							validateVerification: true
						},
						"data[allowClause]": "required"
					},
					messages: {
						/*"data[username]": {
							required: '用户名必填',
							rangelength: $.format('用户名{0}-{1}位,限字母、数字、横线和下划线')
						},*/
						"data[email]": {
							required: '电子邮箱必填',
							email: '请填写正确的电子邮箱'
						},
						"data[password]": {
							required: '密码必填',
							rangelength: $.format('密码必须{0}-{1}位')
						},
						"data[confirm_password]": {
							required: '密码必填',
							equalTo: '两次输入的密码不一致'
						},
						"data[realname]": {
							required: '真实姓名必填'
						},
						"data[phone]": {
							required: '手机必填',
							digits: '手机必须是数字格式',
							rangelength: '手机号必须为11位'
						},
						"data[grade_id]": {
							required: '当前年级必选',
							digits: '请选择当前年级'
						},
						"data[verificationCode]": {
							required: '验证码必填'
						},
						"data[allowClause]": '接受注册条款'
					}
				});
			});
			
			break;
			
		case 'loginForm':
			$.validator.setDefaults({ 
				submitHandler: function(form) { 
					form.submit(); 
				},
				highlight: function(input) {
					$(input).addClass("wss-highlight");
				},
				unhighlight: function(input) {
					$(input).removeClass("wss-highlight");
				}
			}); 
			
			// 自定义验证规则 - 验证用户名格式
			$.validator.addMethod(
				"validateUsername", 
				function(value) {
					var result = value.match(/^[A-Za-z0-9_-]+$/);
					if(result == null) {
						return false;
					} else {
						return true;
					}
				}, 
				'用户名只允许出现字母,数字,下划线,中横线.'
			);
			
			$(function() {
				$("#loginForm").validate({
					errorClass: "validateError",
					onkeyup: false,
					errorPlacement: function(error, element) {
						element.parent("div").nextAll(".fm_submit").after('<div class="validateError"></div>');
						error.appendTo(element.parent("div").nextAll(".fm_submit").next('div[class="validateError"]'));
						//$("div[id='loginErrorMsg']").html(error);
					},
					success: function(label) {
						label.parent("div[class='validateError']").remove();
					},
					rules: {
						"data[login_username]": {
							required: true
							//rangelength: [4, 16],
							//validateUsername: true
						},
						"data[login_password]": {
							required: true,
							rangelength: [6, 16]
						}
					},
					messages: {
						"data[login_username]": {
							required: '用户名必填'
							//rangelength: $.format('用户名{0}-{1}位,限字母、数字、横线和下划线')
						},
						"data[login_password]": {
							required: '密码必填',
							rangelength: $.format('密码必须{0}-{1}位')
						}
					}
				});
			});
			
			break;
			
		default:
			break;
	}
	
};

// 更新验证码图片
function changeVerificationImg(imgId) {
	var newVerificationImg = '/verifications/show?' + generateMixed(12);
	$('img[id="' + imgId + '"]').attr('src', newVerificationImg);
};

// 生成随机字符串
function generateMixed(n) {
	var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    var res = "";
    for(var i = 0; i < n ; i ++) {
        var id = Math.ceil(Math.random() * 35);
        res += chars[id];
    }
    return res;
}; 